<?php

/**
 * SmartPHP framework
 *
 * @name SmartPHP framework
 * @package SmartPHP
 * @author 费尔 <admin@smartphp.cn>
 * @version 1.0 Beta
 * @link http://www.smartphp.cn
 * @copyright smartphp.cn
 * @license <a href="http://www.smartphp.cn">smartphp</a>
 */

namespace Driver\Session;

use \Base\{
    File as F,
    Config
};

class File {

    private $options;

    /**
     * 打开Session
     * @access public
     * @param string $savePath
     * @param mixed  $sessName
     * @return bool
     * @throws Exception
     */
    public function open($savePath, $sessName) {
        $this->options['path'] = Config::get('session.filepath');
        $this->options['path'] = rtrim($this->options['path'], '\\/') . DS;
        return true;
    }

    /**
     * 关闭Session
     * @access public
     */
    public function close() {

        return true;
    }

    /**
     * 读取Session
     * @access public
     * @param string $sessID
     * @return bool|string
     */
    public function read($sessID) {
        $filename = $this->filename($sessID);
        return F::read($filename);
    }

    /**
     * 写入Session
     * @access public
     * @param string $sessID
     * @param String $sessData
     * @return bool
     */
    public function write($sessID, $sessData) {
        $filename = $this->filename($sessID);
        F::set($filename, $sessData);
        return true;
    }

    /**
     * 删除Session
     * @access public
     * @param string $sessID
     * @return bool|void
     */
    public function destroy($sessID) {
        $filename = $this->filename($sessID);
        F::remove($filename);
        return true;
    }

    /**
     * Session 垃圾回收
     * @access public
     * @param string $sessMaxLifeTime
     * @return bool
     */
    public function gc($sessMaxLifeTime) {
        return true;
    }

    /**
     * 取得变量的存储文件名
     *
     * @access private
     * @param string $name 缓存变量名
     * @return string
     */
    private function filename($name) {
        $name = md5(Config::get('authkey') . $name);
        if (Config::get('session.filesubdir')) {
            $dir = '';
            for ($i = 0; $i < Config::get('session.filelevel'); $i ++)
                $dir .= $name{$i} . DS;
            $filename = $dir . $name . '.php';
        } else
            $filename = $name . '.php';
        return $this->options['path'] . $filename;
    }

}
